// components/organisms/TopIcons.js
import React, { useRef, useState, useEffect, forwardRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { createPortal } from 'react-dom';
import { Toolbar, Box, IconButton, Typography, useMediaQuery } from '@mui/material';
import DragHandleIcon from '@mui/icons-material/DragHandle';
import HomeIcon from '@mui/icons-material/Home';
import { Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import { useDarkMode } from 'contexts/DarkMode';
import { useDrawer } from 'contexts/DrawerContext';
import {
  StyledAppBar,
  StyledTypography,
  LogoWrapper,
  FixedLogoText,
  toolbarSx,
  dragHandleIconButtonSx,
  dragHandleIconSx,
  homePageContainerSx,
  homePageBottomBoxSx,
  homePageH1Sx,
  homePageH2Sx,
  fixedLogoContainerSx,
  logoLinkStyle,
  logoTextContainerSx,
  logoTextSx,
  homeIconSx,
  homeIconButtonSx,
  portalButtonSx,
  portalDragIconSx,
  fixedButtonStyle
} from './TopIcons.styles';

// LogoComponent - moved inside as a constant
const LogoComponent = ({
  darkMode = true,
  isHomePage,
  navigateOpen,
  logoText = 'startersaas.pro',
  linkTo = '/',
  showPlayIcon = true,
  isFixed = false,
}) => {
  const location = useLocation();
  const isHomePageRoute = location.pathname === '/home-page';
  
  // Calculate primary color's RGB value
  const calculatePrimaryRgb = (primaryMainColor) => {
    if (primaryMainColor.startsWith('#')) {
      const r = parseInt(primaryMainColor.slice(1, 3), 16);
      const g = parseInt(primaryMainColor.slice(3, 5), 16);
      const b = parseInt(primaryMainColor.slice(5, 7), 16);
      return `${r}, ${g}, ${b}`;
    }
    return '25, 118, 210';
  };

  // Breakpoints
  const isXs = useMediaQuery('(max-width: 599px)');
  const isSm = useMediaQuery('(min-width: 600px) and (max-width: 959px)');
  const isMd = useMediaQuery('(min-width: 960px) and (max-width: 1279px)');
  const isLg = useMediaQuery('(min-width: 1280px) and (max-width: 1919px)');
  const isXl = useMediaQuery('(min-width: 1920px)');

  // Responsive font size determination with 1.5x sizing
  const getFontSize = () => {
    if (isXs) return 'calc(4.5vh + 1.5vw)';
    if (isSm) return 'calc(7.5vh + 1.5vw)';
    if (isMd) return 'calc(8.25vh + 1.5vw)';
    if (isLg) return 'calc(9vh + 1.5vw)';
    if (isXl) return 'calc(9.75vh + 1.5vw)';
    return '6rem';
  };

  // Responsive icon size determination with 1.5x sizing
  const getIconSize = () => {
    if (isXs) return '3rem';
    if (isSm) return '4.05rem';
    if (isMd) return '4.5rem';
    if (isLg) return '4.8rem';
    if (isXl) return '5.25rem';
    return '4.5rem';
  };

  const fontSize = getFontSize();
  const iconSize = getIconSize();

  // Animation variants for fixed logo
  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.15,
        when: "beforeChildren"
      }
    }
  };

  const itemVariants = {
    hidden: { x: -50, opacity: 0 },
    visible: { 
      x: 0, 
      opacity: 1,
      transition: { 
        type: "spring",
        stiffness: 200,
        damping: 20
      }
    }
  };

  // Set CSS variable for primary color
  React.useEffect(() => {
    document.documentElement.style.setProperty(
      '--primary-main-rgb',
      calculatePrimaryRgb('#40d47e')
    );
    
    // Dynamically load the Monoton font if not already present
    const monotonFont = document.createElement('link');
    monotonFont.rel = 'stylesheet';
    monotonFont.href = 'https://fonts.googleapis.com/css2?family=Monoton&display=swap';
    document.head.appendChild(monotonFont);
    
    return () => {
      document.head.removeChild(monotonFont);
    };
  }, []);

  // Render the fixed logo when isFixed is true
  if (isFixed) {
    return (
      <Box 
        component={motion.div}
        variants={containerVariants}
        initial="hidden"
        animate="visible"
        sx={fixedLogoContainerSx}
      >
        <FixedLogoText variants={itemVariants} darkMode={darkMode} isHomePage={isHomePageRoute}>
          Starter
        </FixedLogoText>
        <FixedLogoText variants={itemVariants} darkMode={darkMode} isHomePage={isHomePageRoute}>
          Saas
        </FixedLogoText>
        <FixedLogoText variants={itemVariants} darkMode={darkMode} isHomePage={isHomePageRoute}>
          .pro
        </FixedLogoText>
      </Box>
    );
  }

  // Render the original logo when not fixed
  return (
    <LogoWrapper className="logo-component">
      <Link
        to={linkTo}
        style={logoLinkStyle}
      >
        <Box sx={logoTextContainerSx}>
          <StyledTypography fontSize={fontSize} darkMode={darkMode} isHomePage={isHomePageRoute} sx={logoTextSx}>
            Starter
          </StyledTypography>
          <StyledTypography fontSize={fontSize} darkMode={darkMode} isHomePage={isHomePageRoute} sx={logoTextSx}>
            Saas
          </StyledTypography>
          <StyledTypography fontSize={fontSize} darkMode={darkMode} isHomePage={isHomePageRoute} sx={logoTextSx}>
            .pro
          </StyledTypography>
        </Box>
      </Link>
      {showPlayIcon && (
        <IconButton
          aria-label="dashboard"
          onClick={navigateOpen}
          size="large"
          sx={homeIconButtonSx(iconSize)}
        >
          <HomeIcon
            sx={homeIconSx(iconSize, darkMode, isHomePageRoute)}
          />
        </IconButton>
      )}
    </LogoWrapper>
  );
};

// PortalDraghandleButton - moved inside as a constant
const PortalDraghandleButton = forwardRef(({
  isOpen = false,
  onToggle = () => {},
  id = "draghandle-button",
  className = "",
  portalId = "draghandle-portal",
  zIndex = 100000,
  darkMode = false,
  ...props
}, ref) => {
  const [portalElement, setPortalElement] = useState(null);
  
  // Create portal container on mount
  useEffect(() => {
    let element = document.getElementById(portalId);
    
    if (!element) {
      element = document.createElement('div');
      element.id = portalId;
      element.style.position = 'fixed';
      element.style.top = '0';
      element.style.left = '0';
      element.style.width = '0';
      element.style.height = '0';
      element.style.zIndex = zIndex;
      document.body.appendChild(element);
    }
    
    setPortalElement(element);
    
    return () => {
      if (element && element.parentNode && element.childNodes.length <= 1) {
        document.body.removeChild(element);
      }
    };
  }, [portalId, zIndex]);
  
  const buttonComponent = (
    <IconButton
      ref={ref}
      color="primary"
      aria-label="menu"
      onClick={onToggle}
      id={id}
      className={className}
      sx={portalButtonSx(darkMode, props.style)}
      {...props}
    >
      <DragHandleIcon sx={portalDragIconSx(darkMode)} />
    </IconButton>
  );
  
  if (!portalElement) {
    return null;
  }
  
  return createPortal(buttonComponent, portalElement);
});

PortalDraghandleButton.displayName = 'PortalDraghandleButton';

const TopIcons = ({ isXs, isHomePage: propsIsHomePage, useTheme }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const { darkMode } = useDarkMode();
  const { drawerOpen, toggleDrawer } = useDrawer();
  
  // Check if we're on the home page
  const isHomePage = location.pathname === '/home-page';
  
  const [showFixedButton, setShowFixedButton] = useState(false);
  const [showIconButton, setShowIconButton] = useState(true);
  const [isLogoFixed, setIsLogoFixed] = useState(false);
  const [buttonCoords, setButtonCoords] = useState({ right: 0 });
  
  const toolbarRef = useRef(null);
  const dragHandleRef = useRef(null);
  
  const calculatePosition = () => {
    if (dragHandleRef.current) {
      const rect = dragHandleRef.current.getBoundingClientRect();
      const viewportWidth = window.innerWidth;
      const right = viewportWidth - rect.right;
      setButtonCoords({ right });
    }
  };
  
  const handleScroll = () => {
    const scrollY = window.scrollY;
    const toolbarBottom = toolbarRef.current ? toolbarRef.current.getBoundingClientRect().bottom : 0;
    
    const nowScrolledDown = scrollY > 0 && toolbarBottom <= 0;
    
    if (nowScrolledDown) {
      setShowFixedButton(true);
      setShowIconButton(false);
      setIsLogoFixed(true);
      calculatePosition();
    } else {
      setShowFixedButton(false);
      setShowIconButton(true);
      setIsLogoFixed(false);
    }
  };
  
  useEffect(() => {
    calculatePosition();
    window.addEventListener('scroll', handleScroll);
    window.addEventListener('resize', calculatePosition);
    
    return () => {
      window.removeEventListener('scroll', handleScroll);
      window.removeEventListener('resize', calculatePosition);
    };
  }, []);
  
  // eslint-disable-next-line
  const navigatePage = (url) => {
    window.open(url, '_blank', 'noopener,noreferrer');
  };

  const navigateOpen = (path) => {
    if (path === 'toggleDrawer') {
      toggleDrawer();
    } else {
      navigate(path);
    }
  };
  
  // AppBar component with the same structure and props as before
  const appBarContent = (
    <StyledAppBar 
      position="static" 
      elevation={0} 
      color="transparent" 
      isHomePage={isHomePage}
    >
      <Toolbar ref={toolbarRef} sx={toolbarSx}>
        {/* Logo Component on the left */}
        <LogoComponent 
          darkMode={darkMode} 
          isHomePage={isHomePage} 
          navigateOpen={() => navigateOpen('/')}
          logoText='startersaas.pro'
          isFixed={isLogoFixed}
        />
        
        {/* DragHandle IconButton on the right */}
        {showIconButton && (
          <IconButton 
            ref={dragHandleRef}
            color="primary"
            aria-label="menu"
            onClick={() => toggleDrawer()}
            id="draghandle"
            className="my-custom-class"
            sx={dragHandleIconButtonSx(darkMode)}
          >
            <DragHandleIcon sx={dragHandleIconSx(darkMode)} />
          </IconButton>
        )}
      </Toolbar>
    </StyledAppBar>
  );
  
  // Conditional rendering based on route
  if (isHomePage) {
    return (
      <Box sx={homePageContainerSx}>
        {/* AppBar at the top with same structure */}
        {appBarContent}
        
        {/* Typography at the bottom */}
        <Box sx={homePageBottomBoxSx}>
          <Typography 
            variant="h3" 
            component="h1" 
            sx={homePageH1Sx}
          >
            Premium FSBO Leads for Agents
          </Typography>
          <Typography 
            variant="h4" 
            component="h2" 
            sx={homePageH2Sx}
          >
            Launch Your Property Listing Referral Today
          </Typography>
        </Box>
        
        {/* Portal Button that appears when scrolled down (outside toolbar) */}
        {!showIconButton && showFixedButton && (
          <PortalDraghandleButton 
            isOpen={drawerOpen}
            onToggle={() => toggleDrawer()}
            id="draghandle-fixed" 
            className="my-custom-class"
            darkMode={darkMode}
            style={fixedButtonStyle(buttonCoords)}
          />
        )}
      </Box>
    );
  }
  
  // Default rendering for non-home pages
  return (
    <>
      {appBarContent}
      
      {/* Portal Button that appears when scrolled down (outside toolbar) */}
      {!showIconButton && showFixedButton && (
        <PortalDraghandleButton 
          isOpen={drawerOpen}
          onToggle={() => toggleDrawer()}
          id="draghandle-fixed" 
          className="my-custom-class"
          darkMode={darkMode}
          style={fixedButtonStyle(buttonCoords)}
        />
      )}
    </>
  );
};

export default TopIcons;